package com.jz.community.moduleshoppingguide.nearshop.ui.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.widget.Space;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.gyf.barlibrary.ImmersionBar;
import com.jz.community.basecomm.base.BaseMvpSupportActivity;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.bean.baseCartInfo.NewAddCartInfo;
import com.jz.community.basecomm.bean.baseGoods.BaseGoodsInfo;
import com.jz.community.basecomm.bean.baseGoods.GoodInfo;
import com.jz.community.basecomm.bean.baseGoods.ShopInfo;
import com.jz.community.basecomm.bean.baseGoods.ShopListInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.constant.ConstantErrorCode;
import com.jz.community.basecomm.net.rxandroid.OnLoadListener;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.AddCartTask;
import com.jz.community.basecomm.task.GetGoodsSkuTask;
import com.jz.community.basecomm.utils.BaseImageLoaderUtils;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.CharacterUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxTimeTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.basecomm.utils.intentUtils.OrderIntentUtils;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToCartRefreshEvent;
import com.jz.community.commview.banner.Banner;
import com.jz.community.commview.banner.BannerConfig;
import com.jz.community.commview.banner.Transformer;
import com.jz.community.commview.view.MyStateView;
import com.jz.community.commview.view.RelativePopupWindow;
import com.jz.community.commview.view.widget.ProgressDialogManager;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.home.utils.BannerGlideImageLoader;
import com.jz.community.moduleshoppingguide.nearshop.bean.CartGoodInfo;
import com.jz.community.moduleshoppingguide.nearshop.bean.GoodsInfo;
import com.jz.community.moduleshoppingguide.nearshop.bean.NearShopCategoryBean;
import com.jz.community.moduleshoppingguide.nearshop.bean.NearShopGoodsRight;
import com.jz.community.moduleshoppingguide.nearshop.bean.NewCartListInfo;
import com.jz.community.moduleshoppingguide.nearshop.bean.ShopInfoBean;
import com.jz.community.moduleshoppingguide.nearshop.model.NearShopModel;
import com.jz.community.moduleshoppingguide.nearshop.model.NearShopModelImp;
import com.jz.community.moduleshoppingguide.nearshop.presenter.NearShopGoodsPresenter;
import com.jz.community.moduleshoppingguide.nearshop.task.GetShopCartListTask;
import com.jz.community.moduleshoppingguide.nearshop.ui.NearShopGoodsView;
import com.jz.community.moduleshoppingguide.nearshop.ui.adapter.DownstairGoodsAdapter;
import com.jz.community.moduleshoppingguide.nearshop.ui.adapter.DownstairTypeAdapter;
import com.jz.community.moduleshoppingguide.nearshop.ui.adapter.SelectedGoodsAdapter;
import com.jz.community.moduleshoppingguide.nearshop.ui.view.AddWidget;
import com.jz.community.moduleshoppingguide.nearshop.ui.view.NearShopInfoPopWindow;
import com.jz.community.moduleshoppingguide.nearshop.ui.view.ShareShopPopUp;
import com.jz.community.moduleshoppingguide.nearshop.ui.view.ShopCarView;
import com.jz.community.moduleshoppingguide.nearshop.ui.view.StandardPop;
import com.jz.community.moduleshoppingguide.nearshop.utils.AppBarStateChangeListener;
import com.jz.community.moduleshoppingguide.nearshop.utils.ViewUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;


public class NearShopGoodsActivity extends BaseMvpSupportActivity<NearShopGoodsView.View, NearShopGoodsPresenter> implements NearShopGoodsView.View, SelectedGoodsAdapter.IChangListener, BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R2.id.nearshop_toolbar)
    Toolbar nearshopToolbar;
    @BindView(R2.id.space)
    Space space;
    @BindView(R2.id.nearshop_toolbar_title)
    TextView nearshopToolbarTitle;
    @BindView(R2.id.nearshop_title)
    TextView nearshopTitle;
    @BindView(R2.id.tv_on_sale_count)
    TextView onSaleCount;
    @BindView(R2.id.nearshop_avatar)
    CircleImageView nearshopAvatar;
    @BindView(R2.id.nearshop_app_bar)
    AppBarLayout nearshopAppBar;
    @BindView(R2.id.stair_type_rv)
    RecyclerView stairTypeRv;
    @BindView(R2.id.stair_goods_rv)
    RecyclerView stairGoodsRv;
    @BindView(R2.id.iv_pull_bottom)
    ImageView ivPullBottom;
    @BindView(R2.id.rl_nearshop_pingjia)
    RelativeLayout rlNearshopPingjia;
    @BindView(R2.id.near_goods_parent)
    CoordinatorLayout nearGoodsParent;
    @BindView(R2.id.cart_view)
    ShopCarView cartView;
    @BindView(R2.id.ll_selected_goods_clear)
    LinearLayout llSelectedGoodsClear;
    @BindView(R2.id.selected_goods_rv)
    RecyclerView selectedGoodsRv;


    //详情
    @BindView(R2.id.iv_goods_detail_pop_close)
    ImageView ivGoodsDetailPopClose;
    @BindView(R2.id.tv_goods_detail_pop_explain)
    TextView tvGoodsDetailPopExplain;
    @BindView(R2.id.rl_goods_detail_pop_explain)
    RelativeLayout rlGoodsDetailPopExplain;
    @BindView(R2.id.ll_Goods_detail_banner_and_explain)
    LinearLayout llGoodsDetailBannerAndExplain;
    @BindView(R2.id.tv_goods_detail_pop_goods_name)
    TextView tvGoodsDetailPopGoodsName;
    @BindView(R2.id.tv_goods_detail_pop_goods_price)
    TextView tvGoodsDetailPopGoodsPrice;
    @BindView(R2.id.tv_goods_detail_pop_goods_discount_price)
    TextView tvGoodsDetailPopGoodsDiscountPrice;
    @BindView(R2.id.goods_detail_userIcon_recyclerView)
    RecyclerView goodsDetailUserIconRecyclerView;
    @BindView(R2.id.goods_detail_rating_bar)
    MaterialRatingBar goodsDetailRatingBar;
    @BindView(R2.id.ll_user_icon_ratting)
    LinearLayout llUserIconRatting;
    @BindView(R2.id.tv_goods_detail_pop_total)
    TextView tvGoodsDetailPopTotal;
    @BindView(R2.id.goods_detail_rattingBar_evaluate)
    MaterialRatingBar goodsDetailRattingBarEvaluate;
    @BindView(R2.id.ll_goods_detail_pop_evaluate)
    LinearLayout llGoodsDetailPopEvaluate;
    @BindView(R2.id.goods_detail_evaluate_recycler)
    RecyclerView goodsDetailEvaluateRecycler;
    @BindView(R2.id.near_goods_detail_goods_banner)
    Banner nearGoodsDetailGoodsBanner;
    @BindView(R2.id.tv_ratting_bar_score)
    TextView tvRattingBarScore;
    @BindView(R2.id.tv_ratting_bar_score_one)
    TextView tvRattingBarScoreOne;
    @BindView(R2.id.fl_banner_parent)
    FrameLayout flBannerParent;
    @BindView(R2.id.tv_line)
    TextView tvLine;
    @BindView(R2.id.ll_evaluate_list)
    LinearLayout llEvaluateList;
    @BindView(R2.id.add_widget)
    AddWidget addWidget;
    @BindView(R2.id.rl_bg)
    RelativeLayout rlBg;

    @BindView(R2.id.iv_near_shop_back)
    ImageView ivNearShopBack;
    @BindView(R2.id.iv_near_shop_share)
    ImageView ivNearShopShare;
    @BindView(R2.id.near_goods_search_edit)
    EditText nearGoodsSearchEdit;
    @BindView(R2.id.near_goods_search_enter)
    RelativeLayout nearGoodsSearchEnter;


    private AppBarStateChangeListener mAppBarStateChangeListener;
    private int[] mAvatarPoint = new int[2], mSpacePoint = new int[2],
            mToolbarTextPoint = new int[2], mTitleTextViewPoint = new int[2];
    private final static float EXPAND_AVATAR_SIZE_DP = 70f;
    private final static float COLLAPSED_AVATAR_SIZE_DP = 32f;
    private float mTitleTextSize;
    private String shopId;
    private String gid;
    private String name;
    private String logo;
    private String business_status = "1";
    private DownstairTypeAdapter typeAdapter;
    private DownstairGoodsAdapter goodsAdapter;
    private LinearLayoutManager typeLayoutManager;
    private LinearLayoutManager goodsLayoutManager;
    private NearShopInfoPopWindow shopInfoPopWindow;
    BottomSheetBehavior behavior;
    BottomSheetBehavior detailBehavior;
    SelectedGoodsAdapter adapter;
    private boolean isShowPop = false;
    private String send_type;
    private ShopInfoBean shopInfoBean;
    private ShareShopPopUp shareShopPopUp;
    private int page = 0;
    private int size = 10;
    private String categoryId;
    private View noDataView;
    MyStateView myStateView;
    private ImmersionBar immersionBar;

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected int getContentView() {
        return R.layout.module_shoppingguide_activity_near_shop_goods;
    }

    @Override
    protected NearShopGoodsPresenter createPresenter() {
        return new NearShopGoodsPresenter(this);
    }

    @Override
    protected void initView() {
        immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarColor(R.color.color_user_bg).fitsSystemWindows(true).init();
        mTitleTextSize = nearshopTitle.getTextSize();
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int WindowHeight = wm.getDefaultDisplay().getHeight();
        int WindowWidth = wm.getDefaultDisplay().getWidth();
        myStateView = new MyStateView();
        noDataView = myStateView.getNoDataView(this, (ViewGroup) stairGoodsRv.getParent(), "暂无商品！", null);
        typeLayoutManager = new LinearLayoutManager(this);
        stairTypeRv.setLayoutManager(typeLayoutManager);
        typeAdapter = new DownstairTypeAdapter(R.layout.module_shoppingguide_item_downstair_type, new ArrayList<>());
        stairTypeRv.setAdapter(typeAdapter);
        goodsLayoutManager = new LinearLayoutManager(this);
        stairGoodsRv.setLayoutManager(goodsLayoutManager);
        goodsAdapter = new DownstairGoodsAdapter(R.layout.module_shoppingguide_item_stair_goods, new ArrayList<>());
        stairGoodsRv.setAdapter(goodsAdapter);
        /**
         * 底部显示当前已选商品列表部分
         */
        behavior = BottomSheetBehavior.from(findViewById(R.id.selected_bottom_sheet));
        //默认隐藏
        behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        //设置弹出高度
        behavior.setPeekHeight(WindowHeight);
        behavior.setBottomSheetCallback(bottomSheetCallback);
        selectedGoodsRv.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new SelectedGoodsAdapter(R.layout.module_shoppingguide_item_selected_goods, new ArrayList<>(), shopId);
        selectedGoodsRv.setAdapter(adapter);
        adapter.setChangListener(this);
        /**
         *底部显示商品详情
         */
        detailBehavior = BottomSheetBehavior.from(findViewById(R.id.detail_bottom_sheet));
        //设置弹出高度
        detailBehavior.setPeekHeight(WindowWidth + 500);
        //默认隐藏
        detailBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        detailBehavior.setBottomSheetCallback(bottomSheetCallback);
        ViewGroup.LayoutParams lp_banner = nearGoodsDetailGoodsBanner.getLayoutParams();
        lp_banner.height = WindowWidth;
        nearGoodsDetailGoodsBanner.setLayoutParams(lp_banner);
        //设置banner样式
        nearGoodsDetailGoodsBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        nearGoodsDetailGoodsBanner.setImageLoader(new BannerGlideImageLoader());
        //设置banner动画效果
        nearGoodsDetailGoodsBanner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        nearGoodsDetailGoodsBanner.isAutoPlay(true);
        //设置轮播时间
        nearGoodsDetailGoodsBanner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        nearGoodsDetailGoodsBanner.setIndicatorGravity(BannerConfig.RIGHT);
        nearGoodsDetailGoodsBanner.startAutoPlay(true);
        EventBus.getDefault().register(this);
    }

    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventBus(AppEvent message) {
        if (message.tag == EventConfig.ORDER_REFRESH) {
            finish();
        }
    }

    @Override
    protected void initDatas() {
        shopId = getIntent().getStringExtra("shopId");
        gid = getIntent().getStringExtra("gid");
        mPresenter.nearShopInfoes(shopId);
        balanceAccounts();
    }

    @Override
    protected void addListener() {
        ivNearShopBack.setOnClickListener(v -> finish());
        mAppBarStateChangeListener = new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {

            }

            @Override
            public void onOffsetChanged(State state, float offset) {
                translationView(offset);
            }
        };
        nearshopAppBar.addOnOffsetChangedListener(mAppBarStateChangeListener);
        ivPullBottom.setOnClickListener(v -> {
            if (shopInfoPopWindow == null) {
                isShowPop = true;
                mPresenter.nearShopInfoes(shopId);
            } else {
                shopInfoPopWindow.showOnAnchor(ivPullBottom, RelativePopupWindow.VerticalPosition.BELOW, RelativePopupWindow.HorizontalPosition.ALIGN_LEFT, 0, 0);
            }
        });
        goodsAdapter.setEnableLoadMore(false);
        goodsAdapter.setOnLoadMoreListener(this, stairGoodsRv);
        addRvListener();
    }


    @Override
    public void showNearShopCategory(List<NearShopCategoryBean> categoryBeanList) {
        if (!Preconditions.isNullOrEmpty(categoryBeanList)) {
            typeAdapter.setNewData(categoryBeanList);
            typeAdapter.setChick(0);
            page = 0;
            categoryId = categoryBeanList.get(0).getId();
            mPresenter.getNearShopGoods(page, size, shopId, categoryId, "", AppConstants.ONREFRESH);
        }
    }

    @Override
    public void showNearShopGoods(BaseGoodsInfo goodsList, int type) {
        if (!Preconditions.isNullOrEmpty(goodsList) && !Preconditions.isNullOrEmpty(goodsList.get_embedded()) && !Preconditions.isNullOrEmpty(goodsList.get_embedded().getContent())) {
            List<NearShopGoodsRight> list = getRightData(goodsList.get_embedded().getContent());
            if (list.size() > 0) {
                if (type == AppConstants.ONREFRESH) {
                    goodsAdapter.setNewData(list);
                } else if (type == AppConstants.ONLOADMORE) {
                    goodsAdapter.addData(list);
                    goodsAdapter.loadMoreComplete();
                } else if (type == AppConstants.ONSEARCH) {
                    goodsAdapter.setNewData(list);
                    typeAdapter.setChickForId(list.get(0).getParentId());
                }
            } else {
                if (type == AppConstants.ONREFRESH) {
                    goodsAdapter.getData().clear();
                    goodsAdapter.setEmptyView(noDataView);
                    goodsAdapter.notifyDataSetChanged();
                } else if (type == AppConstants.ONLOADMORE) {
                    goodsAdapter.loadMoreEnd();
                } else if (type == AppConstants.ONSEARCH) {
                    WpToast.l(getContext(), "没有搜索到数据");
                }
            }
        } else {
            if (type == AppConstants.ONREFRESH) {
                goodsAdapter.getData().clear();
                goodsAdapter.setEmptyView(noDataView);
                goodsAdapter.notifyDataSetChanged();
            } else if (type == AppConstants.ONLOADMORE) {
                goodsAdapter.loadMoreEnd();
            } else if (type == AppConstants.ONSEARCH) {
                WpToast.l(getContext(), "没有搜索到数据");
            }
        }
    }


    private void addRvListener() {
        typeAdapter.setClickListener((String id) -> {
            categoryId = id;
            page = 0;
            mPresenter.getNearShopGoods(page, size, shopId, categoryId, "", AppConstants.ONREFRESH);
        });

        goodsAdapter.setAddClick(new DownstairGoodsAdapter.itemAddClick() {
            @Override
            public void onAddClick(View view, AddWidget addWidget, NearShopGoodsRight goodsRight, int count) {
                if (goodsRight.getSkuInfos().size() > 1) {
                    //多规格
                    StandardPop standardPop = StandardPop.newInstance(goodsRight);
                    standardPop.show(getSupportFragmentManager(), "Dialog");
                    standardPop.setGetSkuBean((skName, skId, price, sId) -> {
                        if (!TextUtils.isEmpty(skName) && !TextUtils.isEmpty(skId) && !TextUtils.isEmpty(price) && !TextUtils.isEmpty(sId)) {
                            getGoodsSkuStatus(view, addWidget, goodsRight, count, price, sId);
                        } else {
                            WpToast.l(getContext(), "获取规格失败");
                        }
                    });
                } else {
                    if (!TextUtils.isEmpty(goodsRight.getSkuInfos().get(0).getDiscountPrice())) {
                        //单规格
                        getGoodsSkuStatus(view, addWidget, goodsRight, count, goodsRight.getSkuInfos().get(0).getDiscountPrice(), goodsRight.getSkuInfos().get(0).getId() + "");
                    } else {
                        getGoodsSkuStatus(view, addWidget, goodsRight, count, goodsRight.getSkuInfos().get(0).getPrice(), goodsRight.getSkuInfos().get(0).getId() + "");
                    }
                }
            }

            @Override
            public void onSubClick(AddWidget addWidget, NearShopGoodsRight goodsRight, int count) {
                getShopCart();
            }

            @Override
            public void onNumClick(NearShopGoodsRight goodsRight, AddWidget addWidget) {

            }
        });

        cartView.setOnAccountClick(type -> {
            //弹出已选列表
            if (type == 1) {
                if (BaseUserUtils.getIsLogin(getContext())) {
                    if (!isBehaviorShowing(behavior) && cartView.isHaveGoods()) {
                        getShopCart();
                    } else {
                        behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                    }
                } else {
                    ARouter.getInstance().build(RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN).navigation();
                }
            } else if (type == 2) {
                //跳转到下单
                placeAnOrder();
            }
        });

        goodsAdapter.setGoodsDetail(goodsRight -> {
            addWidget.setCount(goodsRight.getCount());
            mPresenter.getGoodsInfoes("id::" + goodsRight.getId() + "|shopType::2", 0, 10, goodsRight);
        });

        llSelectedGoodsClear.setOnClickListener(v -> clearShopCartGoods());

        ivNearShopShare.setOnClickListener(v -> showShareGoodsPop());

        nearGoodsSearchEdit.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String name = nearGoodsSearchEdit.getText().toString();
                //搜索
                if (!TextUtils.isEmpty(name)) {
                    mPresenter.getNearShopGoods(page, size, shopId, "", name, AppConstants.ONSEARCH);
                } else {
                    mPresenter.getNearShopGoods(page, size, shopId, "", "", AppConstants.ONREFRESH);
                }
            }
            return false;
        });

        nearGoodsSearchEnter.setOnClickListener(v -> {
            String name = nearGoodsSearchEdit.getText().toString();
            //搜索
            if (!TextUtils.isEmpty(name)) {
                mPresenter.getNearShopGoods(page, size, shopId, "", name, AppConstants.ONSEARCH);
            } else {
                mPresenter.getNearShopGoods(page, size, shopId, "", "", AppConstants.ONREFRESH);
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        mPresenter.getNearShopGoods(page, size, shopId, categoryId, "", AppConstants.ONLOADMORE);
    }


    /**
     * 限购添加库存数量
     */
    private void getGoodsSkuStatus(View view, AddWidget addWidget, NearShopGoodsRight goodsRight, int count, String price, String sId) {
        new GetGoodsSkuTask(this, o -> {
            BaseResponseInfo baseResponseInfo = (BaseResponseInfo) o;
            if (!Preconditions.isNullOrEmpty(baseResponseInfo)) {
                if (baseResponseInfo.getCode() == ConstantErrorCode.SUCC_CODE) {
                    addShopCart(view, addWidget, goodsRight, count, price, sId);
                } else {
                    WpToast.l(NearShopGoodsActivity.this, baseResponseInfo.getMessage());
                }
            }
        }).execute(goodsRight.getId(), count + "");
    }


    private void clearShopCartGoods() {
        if (adapter.getData().size() > 0) {
            List<Long> list = new ArrayList<>();
            for (int i = 0; i < adapter.getData().size(); i++) {
                list.add(Long.parseLong(adapter.getData().get(i).getId() + ""));
            }
            Long[] longArr = new Long[list.size()];
            list.toArray(longArr);
            NearShopModel nearShopModel = new NearShopModelImp(this);
            nearShopModel.deleteCartGoodsInfo(longArr, new OnLoadListener<BaseResponseInfo>() {
                @Override
                public void onSuccess(BaseResponseInfo baseResponseInfo) {
                    adapter.getData().clear();
                    adapter.notifyDataSetChanged();
                    behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                    balanceAccounts();
                    ToCartRefreshEvent toCartRefreshEvent = new ToCartRefreshEvent();
                    toCartRefreshEvent.setShopCartRefresh(true);
                    RxBus.getInstance().post(toCartRefreshEvent);
                }

                @Override
                public void onFail(String s, int code) {
                    WpToast.l(getContext(), s);
                }
            });
        }
    }

    //添加购物车
    private void addShopCart(View view, AddWidget addWidget, NearShopGoodsRight goodsRight, int count, String price, String sId) {
        if (BaseUserUtils.getIsLogin(getContext())) {
            new AddCartTask(NearShopGoodsActivity.this, o -> {
                NewAddCartInfo newAddCartInfo = (NewAddCartInfo) o;
                if (!Preconditions.isNullOrEmpty(newAddCartInfo) && !Preconditions.isNullOrEmpty(newAddCartInfo.getShopId())) {
                    if (goodsRight.getCount() == 0) {
                        addWidget.addAnim(300);
                    }
                    ViewUtil.addTvAnim(view, cartView.carLoc, getContext(), nearGoodsParent);
                    goodsRight.setCartId(newAddCartInfo.getId() + "");
                    goodsRight.setTotalPrice(goodsRight.getTotalPrice() + Double.parseDouble(price));
                    modifyData(addWidget, goodsRight, count);
                    ToCartRefreshEvent toCartRefreshEvent = new ToCartRefreshEvent();
                    toCartRefreshEvent.setShopCartRefresh(true);
                    RxBus.getInstance().post(toCartRefreshEvent);
                } else {
                    WpToast.l(getContext(), "加入购物车失败");
                    addWidget.resetCount(1);
                }
            }).execute("2", goodsRight.getId(), "1", goodsRight.getShopId(), sId, "");
        } else {
            ARouter.getInstance().build(RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN).navigation();
        }
    }


    private void modifyData(AddWidget addWidget, NearShopGoodsRight goodsRight, int count) {
        goodsRight.setCount(count);
        addWidget.setTvText(count);
        balanceAccounts();
    }

    private void balanceAccounts() {
        new GetShopCartListTask(this, o -> {
            NewCartListInfo newCartListInfo = (NewCartListInfo) o;
            if (!Preconditions.isNullOrEmpty(newCartListInfo) && !Preconditions.isNullOrEmpty(newCartListInfo.getValidGoods())) {
                if (newCartListInfo.getValidGoods() != null && newCartListInfo.getValidGoods().size() > 0) {
                    int count = 0;
                    double price = 0;
                    List<CartGoodInfo> cartGoodlist = getCartList(newCartListInfo);
                    for (int i = 0; i < cartGoodlist.size(); i++) {
                        count += cartGoodlist.get(i).getNum();
                        price += cartGoodlist.get(i).getNum() * Double.parseDouble(cartGoodlist.get(i).getPrice());
                    }
                    dealCar(count, CharacterUtils.roundByGoodPrice(price), send_type);
                }
            }
        }).execute();
    }

    private void dealCar(int total_num, String total_price, String send_type) {
        cartView.updateCartData(total_price, total_num, Integer.parseInt(business_status), send_type);
        cartView.showBadge(total_num);
    }


    private List<NearShopGoodsRight> getRightData(List<BaseGoodsInfo.EmbeddedBeanXX.ContentBeanX> list) {
        List<NearShopGoodsRight> goodsRightList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            NearShopGoodsRight goodsRight = new NearShopGoodsRight();
            if (!TextUtils.isEmpty(list.get(i).getSkuInfos().get(0).getPrice())) {
                goodsRight.setPrice(CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(list.get(i).getSkuInfos().get(0).getPrice())));
            }
            if (!TextUtils.isEmpty(list.get(i).getSkuInfos().get(0).getDiscountPrice())) {
                goodsRight.setDiscountPrice(CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(list.get(i).getSkuInfos().get(0).getDiscountPrice())));
            }
            goodsRight.setId(list.get(i).getId() + "");
            goodsRight.setImage(list.get(i).getIcon());
            goodsRight.setParentType(list.get(i).get_embedded().getCategory().getName());
            goodsRight.setTitle(list.get(i).getTitle());
            goodsRight.setParentId(list.get(i).get_embedded().getCategory().getId());
            goodsRight.setShopId(shopId);
            goodsRight.setSkuPropertiesBeans(list.get(i).getSkuProperties());
            goodsRight.setSkuInfosBeans(list.get(i).getSkuInfos());
            goodsRight.setBuyType(list.get(i).getBuyType());
            //goodsRight.setLimitedNum(list.get(i).getLimitedNum());
            goodsRight.setStock(list.get(i).getStock());
            int catCount = 0;
            double totalPrice = 0;
            if (list.get(i).getSkuInfos() != null && list.get(i).getSkuInfos().size() > 0) {
                for (int j = 0; j < list.get(i).getSkuInfos().size(); j++) {
                    catCount += list.get(i).getSkuInfos().get(j).getCatNum();
                    double price;
                    if (!TextUtils.isEmpty(list.get(i).getSkuInfos().get(j).getDiscountPrice())) {
                        price = list.get(i).getSkuInfos().get(j).getCatNum() * Double.parseDouble(list.get(i).getSkuInfos().get(j).getDiscountPrice());
                    } else {
                        price = list.get(i).getSkuInfos().get(j).getCatNum() * Double.parseDouble(list.get(i).getSkuInfos().get(j).getPrice());
                    }
                    totalPrice += price;
                }
            }
            goodsRight.setCount(catCount);
            goodsRight.setTotalPrice(totalPrice);
            goodsRightList.add(goodsRight);
        }
        return goodsRightList;
    }

    @Override
    public void showError(String s) {

    }

    @Override
    public void showNearShopInfoes(ShopInfoBean shopInfoBean) {
        if (isShowPop) {
            shopInfoPopWindow = new NearShopInfoPopWindow(this, shopInfoBean);
            shopInfoPopWindow.showOnAnchor(ivPullBottom, RelativePopupWindow.VerticalPosition.BELOW, RelativePopupWindow.HorizontalPosition.ALIGN_LEFT, 0, 0);
        } else {
            if (shopInfoBean != null) {
                name = shopInfoBean.getName();
                logo = shopInfoBean.getLogo();
                nearshopTitle.setText(name);
                onSaleCount.setText("在售商品" + shopInfoBean.getOnlineGoodsCount() + "件");
                BaseImageLoaderUtils.getInstance().loadDefaltImage(this, nearshopAvatar, logo);
                send_type = shopInfoBean.getSend_type();
                this.shopInfoBean = shopInfoBean;
                if (!TextUtils.isEmpty(shopInfoBean.getBusinessStartHours()) && !TextUtils.isEmpty(shopInfoBean.getBusinessEndHours())) {
                    try {
                        if (RxTimeTool.compare(shopInfoBean.getBusinessStartHours())) {
                            business_status = "0";
                        } else if (RxTimeTool.compare(shopInfoBean.getBusinessEndHours())) {
                            business_status = "1";
                        } else {
                            business_status = "0";
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            /**
             * 得到商铺信息后加载类目
             */
            mPresenter.nearShopCategory(shopId);
        }
    }


    private void getShopCart() {
        if (BaseUserUtils.getIsLogin(getContext())) {
            new GetShopCartListTask(this, o -> {
                NewCartListInfo newCartListInfo = (NewCartListInfo) o;
                if (!Preconditions.isNullOrEmpty(newCartListInfo) && !Preconditions.isNullOrEmpty(newCartListInfo.getValidGoods())) {
                    if (newCartListInfo.getValidGoods() != null && newCartListInfo.getValidGoods().size() > 0) {
                        adapter.setNewData(getCartList(newCartListInfo));
                        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                        rlBg.setBackgroundColor(Color.parseColor("#26000000"));
                    }
                }
            }).execute();
        } else {
            ARouter.getInstance().build(RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN).navigation();
        }
    }

    private void placeAnOrder() {
        new GetShopCartListTask(this, o -> {
            NewCartListInfo newCartListInfo = (NewCartListInfo) o;
            if (!Preconditions.isNullOrEmpty(newCartListInfo) && !Preconditions.isNullOrEmpty(newCartListInfo.getValidGoods())) {
                if (newCartListInfo.getValidGoods() != null && newCartListInfo.getValidGoods().size() > 0) {
                    adapter.setNewData(getCartList(newCartListInfo));
                    ShopInfo shopInfo = new ShopInfo();
                    ShopListInfo shopListInfo = new ShopListInfo();
                    shopListInfo.setShopId(shopId);
                    shopInfo.setGoodFrom(0);
                    shopListInfo.setShopName(name);
                    shopInfo.setSendType(ConverterUtils.toInt(send_type));
                    ArrayList<GoodInfo> goodsList = new ArrayList<>();
                    for (int i = 0; i < adapter.getData().size(); i++) {
                        GoodInfo goods = new GoodInfo();
                        goods.setId(adapter.getData().get(i).getGsId());
                        goods.setNums(adapter.getData().get(i).getNum());
                        goods.setImg(adapter.getData().get(i).getIcon());
                        goods.setName(adapter.getData().get(i).getGoodsName());
                        goods.setSkuName(adapter.getData().get(i).getSkuName());
                        goods.setSkuId(adapter.getData().get(i).getSkuId());
                        goods.setCategoryId(adapter.getData().get(i).getCategoryId());
                        goods.setDisCountPrice(adapter.getData().get(i).getDiscountPrice());
                        goods.setPrice(adapter.getData().get(i).getPrice());
                        goodsList.add(goods);
                    }
                    shopListInfo.setGoodsList(goodsList);
                    List<ShopListInfo> shopInfos = new ArrayList<>();
                    shopInfos.add(shopListInfo);
                    shopInfo.setShopList(shopInfos);
                    shopInfo.setCartIds(getIds());
                    OrderIntentUtils.startFromOrderActivity(JSON.toJSONString(shopInfo));
                }
            }
        }).execute();
    }

    private List<CartGoodInfo> getCartList(NewCartListInfo newCartListInfo) {
        List<CartGoodInfo> list = new ArrayList<>();
        for (int i = 0; i < newCartListInfo.getValidGoods().size(); i++) {
            if (newCartListInfo.getValidGoods().get(i).getId().equals(shopId)) {
                list.addAll(newCartListInfo.getValidGoods().get(i).getCartInfos());
            }
        }
        return list;
    }

    private long[] getIds() {
        List<CartGoodInfo> list = adapter.getData();
        long[] ids = new long[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ids[i] = ConverterUtils.toLong(list.get(i).getId() + "");
        }
        return ids;
    }

    private void showShareGoodsPop() {
        if (shareShopPopUp == null) {
            shareShopPopUp = new ShareShopPopUp(this);
            shareShopPopUp.addShopDetailInfo(shopInfoBean, screenShotView(nearGoodsParent));
            shareShopPopUp.showShopSharePopUp(nearshopToolbarTitle);
        } else {
            shareShopPopUp.showShopSharePopUp(nearshopToolbarTitle);
        }
    }


    private Bitmap screenShotView(View view) {
        //开启缓存功能
        view.setDrawingCacheEnabled(true);
        //创建缓存
        view.buildDrawingCache();
        //获取缓存Bitmap
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        return bitmap;
    }


    @Override
    public void onChange(CartGoodInfo item, int type) {
        for (int i = 0; i < goodsAdapter.getData().size(); i++) {
            if (goodsAdapter.getData().get(i).getId().equals(item.getGsId() + "")) {
                if (type == 1) {
                    if (!TextUtils.isEmpty(item.getDiscountPrice())) {
                        goodsAdapter.getData().get(i).setTotalPrice(goodsAdapter.getData().get(i).getTotalPrice() + ConverterUtils.toDouble(item.getDiscountPrice()));
                    } else {
                        goodsAdapter.getData().get(i).setTotalPrice(goodsAdapter.getData().get(i).getTotalPrice() + ConverterUtils.toDouble(item.getPrice()));
                    }
                    goodsAdapter.getData().get(i).setCount(item.getNum());
                } else if (type == 0) {
                    if (!TextUtils.isEmpty(item.getDiscountPrice())) {
                        goodsAdapter.getData().get(i).setTotalPrice(goodsAdapter.getData().get(i).getTotalPrice() - ConverterUtils.toDouble(item.getDiscountPrice()));
                    } else {
                        goodsAdapter.getData().get(i).setTotalPrice(goodsAdapter.getData().get(i).getTotalPrice() - ConverterUtils.toDouble(item.getPrice()));
                    }
                    goodsAdapter.getData().get(i).setCount(item.getNum());
                } else if (type == -1) {
                    goodsAdapter.getData().get(i).setTotalPrice(0);
                    goodsAdapter.getData().get(i).setCount(0);
                }
                goodsAdapter.notifyDataSetChanged();
                balanceAccounts();
                break;
            }
        }
    }

    @Override
    public void isClear() {
        behavior.setState(BottomSheetBehavior.STATE_HIDDEN);
    }

    private void translationView(float offset) {
        float xOffset = -(mAvatarPoint[0] - mSpacePoint[0]) * offset;
        float yOffset = -(mAvatarPoint[1] - mSpacePoint[1]) * offset;
        float xTitleOffset = -(mTitleTextViewPoint[0] - mToolbarTextPoint[0]) * offset;
        float yTitleOffset = -(mTitleTextViewPoint[1] - mToolbarTextPoint[1]) * offset;
        int newSize = SHelper.dp2px(this,
                EXPAND_AVATAR_SIZE_DP - (EXPAND_AVATAR_SIZE_DP - COLLAPSED_AVATAR_SIZE_DP) * offset);
        float newTextSize =
                mTitleTextSize - (mTitleTextSize - nearshopToolbarTitle.getTextSize()) * offset;
        nearshopAvatar.getLayoutParams().width = newSize;
        nearshopAvatar.getLayoutParams().height = newSize;
        nearshopAvatar.setTranslationX(xOffset);
        nearshopAvatar.setTranslationY(yOffset);
        nearshopTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, newTextSize);
        nearshopTitle.setTranslationX(xTitleOffset);
        nearshopTitle.setTranslationY(yTitleOffset);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (!hasFocus) {
            return;
        }
        resetPoints();
    }

    private void resetPoints() {
        clearAnim();
        int avatarSize = SHelper.dp2px(this, EXPAND_AVATAR_SIZE_DP);
        nearshopAvatar.getLocationOnScreen(mAvatarPoint);
        mAvatarPoint[0] -= (avatarSize - nearshopAvatar.getWidth()) / 2;
        space.getLocationOnScreen(mSpacePoint);
        nearshopToolbarTitle.getLocationOnScreen(mToolbarTextPoint);
        mToolbarTextPoint[0] += SHelper.dp2px(this, 16);
        nearshopTitle.post(() -> {
            nearshopTitle.getLocationOnScreen(mTitleTextViewPoint);
            translationView(mAppBarStateChangeListener.getCurrentOffset());
        });
    }

    private void clearAnim() {
        nearshopAvatar.setTranslationX(0);
        nearshopAvatar.setTranslationY(0);
        nearshopTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTitleTextSize);
        nearshopTitle.setTranslationX(0);
        nearshopTitle.setTranslationY(0);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    private BottomSheetBehavior.BottomSheetCallback bottomSheetCallback = new BottomSheetBehavior.BottomSheetCallback() {
        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                if (!isBehaviorShowing(behavior)) {
                    page = 0;
                    mPresenter.getNearShopGoods(page, size, shopId, categoryId, "", AppConstants.ONREFRESH);
                    rlBg.setBackgroundColor(Color.parseColor("#00000000"));
                }
            }
        }

        @Override
        public void onSlide(@NonNull View bottomSheet, float slideOffset) {

        }
    };

    private Boolean isBehaviorShowing(BottomSheetBehavior behavior) {
        return behavior.getState() == BottomSheetBehavior.STATE_COLLAPSED
                || behavior.getState() == BottomSheetBehavior.STATE_EXPANDED
                || behavior.getState() == BottomSheetBehavior.STATE_SETTLING;
    }


    @Override
    public void showGoodsInfoes(GoodsInfo baseGoodsInfo, NearShopGoodsRight goodsRight) {
        if (baseGoodsInfo.get_embedded().getContent() != null && baseGoodsInfo.get_embedded().getContent().size() > 0) {
            detailBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            GoodsInfo.EmbeddedBeanXX.ContentBeanX contentBean = baseGoodsInfo.get_embedded().getContent().get(0);
            List<String> imgUrls = new ArrayList<>();
            imgUrls.add(contentBean.getIcon());
            nearGoodsDetailGoodsBanner.setImages(imgUrls);
            nearGoodsDetailGoodsBanner.start();
            tvGoodsDetailPopGoodsName.setText(contentBean.getTitle());
            tvGoodsDetailPopGoodsPrice.setText("¥" + contentBean.getPrice());
            addDetailListener(goodsRight);
        } else {
            WpToast.l(this, "获取详情失败");
        }
    }


    private void addDetailListener(NearShopGoodsRight goodsRight) {
        addWidget.setNeedSub(false);
        addWidget.setAddClick(new AddWidget.OnAddClick() {
            @Override
            public void onAddClick(View view, AddWidget addWidget, int count) {
                if (goodsRight.getSkuInfos().size() > 1) {
                    //多规格
                    StandardPop standardPop = StandardPop.newInstance(goodsRight);
                    standardPop.show(getSupportFragmentManager(), "Dialog");
                    standardPop.setGetSkuBean((skName, skId, price, sId) -> {
                        if (!TextUtils.isEmpty(skName) && !TextUtils.isEmpty(skId) && !TextUtils.isEmpty(price) && !TextUtils.isEmpty(sId)) {
                            getGoodsSkuStatus(view, addWidget, goodsRight, count, price, sId);
                        } else {
                            WpToast.l(getContext(), "获取规格失败");
                        }
                    });
                } else {
                    //单规格
                    if (!TextUtils.isEmpty(goodsRight.getSkuInfos().get(0).getDiscountPrice())) {
                        getGoodsSkuStatus(view, addWidget, goodsRight, count, goodsRight.getSkuInfos().get(0).getDiscountPrice(), goodsRight.getSkuInfos().get(0).getId() + "");
                    } else {
                        getGoodsSkuStatus(view, addWidget, goodsRight, count, goodsRight.getSkuInfos().get(0).getPrice(), goodsRight.getSkuInfos().get(0).getId() + "");
                    }
                }
            }

            @Override
            public void onSubClick(AddWidget addWidget, int count) {
                detailBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                getShopCart();
            }

            @Override
            public void onNumClick() {

            }
        });
        ivGoodsDetailPopClose.setOnClickListener(v -> detailBehavior.setState(BottomSheetBehavior.STATE_HIDDEN));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
